package com.sinszm.web.exception;

import com.sinszm.common.Response;
import com.sinszm.common.exception.ApiException;
import com.sinszm.common.exception.SqlApiException;
import com.sinszm.common.exception.SystemApiError;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 捕获全局业务异常信息
 *
 * @author chenjianbo
 */
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionResolver.class);

    private String formatTime2Millisecond(Date date) {
        return String.format("%tF %tT.%tL", date, date, date);
    }

    @Override
    public ModelAndView resolveException(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler,
            Exception ex) {
        //设置视图模型
        ModelAndView mav = new ModelAndView();
        mav.setView(new MappingJackson2JsonView());
        mav.setStatus(HttpStatus.OK);
        //异常信息处理
        Map<String, Object> result = new HashMap<>(0);
        if (ex instanceof ApiException) {
            ApiException e = (ApiException) ex;
            result.putAll(Json.fromJsonAsMap(Object.class, Response.fail(e.apiError(), ex.getCause()).toString()));
        } else if (ex instanceof SQLException) {
            SqlApiException e = new SqlApiException();
            result.putAll(Json.fromJsonAsMap(Object.class, Response.fail(e.apiError(), ex.getCause()).toString()));
        } else {
            result.putAll(Json.fromJsonAsMap(Object.class, Response.fail(SystemApiError.SYSTEM_ERROR_01, ex.getCause
                    ()).toString()));
        }
        mav.addAllObjects(result);
        logger.error("异常时间: {}, 异常信息:{}", formatTime2Millisecond(new Date()), Json.toJson(result, JsonFormat.tidy()));
        return mav;
    }
}
